package com.shangxia.study.juc.lock.aqs;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁实现
 *
 * @author zhouya38158
 * @Package com.shangxia.study.juc.lock.aqs
 * @date 2021/10/29 17:22
 */
public class MyReentrantLock implements Luck {

    ReentrantLock lock = new ReentrantLock(true);

    /**
     * 用于判断是否已经锁了
     */
    private boolean isLock;
    /**
     * 用于记录锁的线程
     */
    private Thread lockThread;
    /**
     * 用于记录锁的次数
     */
    private int lockCount;

    @Override
    public synchronized void lock() {
        while (isLock && Thread.currentThread() != lockThread) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        isLock = true;
        lockThread = Thread.currentThread();
        lockCount++;
        if (Integer.MAX_VALUE == lockCount) {
            throw new RuntimeException();
        }
        System.out.println("lockThread=" + lockThread.getName() + ";lockCount=" + lockCount);
    }

    @Override
    public synchronized void unLock() {
        if (isLock && Thread.currentThread() == lockThread) {
            if (--lockCount == 0) {
                isLock = false;
                notify();
            }
        }
        System.out.println("lockThread=" + lockThread.getName() + ";lockCount=" + lockCount);
    }
}
